package cn.edu.jsu.zjj.controller;

import cn.edu.jsu.zjj.annotation.AuthCheck;
import cn.edu.jsu.zjj.common.result.Result;
import cn.edu.jsu.zjj.constant.UserConstant;
import cn.edu.jsu.zjj.model.dto.userWork.UserWorkAddRequest;
import cn.edu.jsu.zjj.model.dto.userWork.UserWorkDeleteRequest;
import cn.edu.jsu.zjj.model.dto.userWork.UserWorkPageRequest;
import cn.edu.jsu.zjj.model.dto.userWork.UserWorkUpdateRequest;
import cn.edu.jsu.zjj.model.entity.UserWork;
import cn.edu.jsu.zjj.model.utils.OtherUtils;
import cn.edu.jsu.zjj.service.UserService;
import cn.edu.jsu.zjj.service.UserWorkService;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.FieldOps;
import cn.zhxu.bs.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/userWork")
@Slf4j
@Api(tags = "用户工作经历管理")
public class UserWorkController {

    @Autowired
    private UserWorkService userWorkService;
    @Autowired
    private BeanSearcher beanSearcher;
    @Autowired
    private UserService userService;
    @PostMapping("/page")
    @ApiOperation(value = "分页查询用户工作经历", notes = "分页查询用户工作经历")
    public Result page(@RequestBody UserWorkPageRequest request){
        if(request == null || request.getUserId() == null){
            return null;
        }
        Long userId = request.getUserId();
        //页码
        Integer page = request.getPageNum();
        //每页大小
        Integer size = request.getPageSize();
        // 解析 startDateTime 和 endDateTime
        LocalDate startDateTime = OtherUtils.transform(request.getStartDate());
        LocalDate endDateTime = OtherUtils.transform(request.getEndDate());

        List<String> fields = Arrays.asList(request.getSideline().split("\\s+"));

        List<UserWork> userWorks = beanSearcher.searchAll(UserWork.class,
                MapUtils.builder()
                        .field(UserWork::getUserId, userId)
                        .field(UserWork::getStartDate, startDateTime, endDateTime).op("bt")
                        .field(UserWork::getCertifier, request.getCertifier()).op("ct")
                        .field(UserWork::getSideline, fields).op("la")
                        .field(UserWork::getIsDeleted, 0)
                        .orderBy(UserWork::getCreateTime).desc()
                        .page(page, size)
                        .build()
        );
        Page<UserWork> userWorkPage = new Page<>(page, size);
        userWorkPage.setRecords(userWorks);
        userWorkPage.setTotal(userWorks.size());
        return Result.success(userWorkPage);
    }

   @PostMapping("/add")
   @ApiOperation(value = "新增用户工作经历", notes = "新增用户工作经历")
   @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.DEFAULT_ROLE})
    public Result add(@RequestBody UserWorkAddRequest request) {
        // 检查请求对象是否为空
        if (request == null||request.getCertifier() == null||request.getStartDate() == null||request.getEndDate() == null||request.getDescription() == null) {
            return Result.error("请求参数不能为空");
        }
        UserWork userWork = new UserWork();
        Long userId = request.getUserId();
        userWork.setUserId(userId);
        userWork.setCreateTime(LocalDateTime.now());
        userWork.setIsDeleted(0);

        // 解析 startDateTime 和 endDateTime
        LocalDate startDateTime = OtherUtils.transform(request.getStartDate());
        LocalDate endDateTime = OtherUtils.transform(request.getEndDate());

        if (startDateTime. isAfter(endDateTime)) {
            return Result.error("结束时间不能早于开始时间");
        }
        // 设置属性
        userWork.setStartDate(startDateTime);
        userWork.setEndDate(endDateTime);
        BeanUtils.copyProperties(request, userWork);

        boolean save = userWorkService.save(userWork);
        return Result.success(save);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除用户工作经历", notes = "删除用户工作经历")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.DEFAULT_ROLE})
    public Result delete(@RequestBody UserWorkDeleteRequest request) {
        // 检查请求对象是否为空
        if (request.getId() == null) {
            return Result.error("请先选择要删除的记录");
        }
        LambdaQueryWrapper<UserWork> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserWork::getId, request.getId());
        wrapper.eq(UserWork::getIsDeleted, 0);
        UserWork userWork = userWorkService.getOne(wrapper);
        if (userWork == null) {
            return Result.error("记录不存在");
        }
        userWork.setIsDeleted(1);
       log.info("Before update: {}", userWork);
       boolean update = userWorkService.saveOrUpdate(userWork);
       log.info("Update result: {}", update);

        return Result.success("删除成功");
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询用户工作经历详情", notes = "查询用户工作经历详情")
    public Result getUserWorkById(@PathVariable("id") Long id) {
        UserWork userWork = userWorkService.getById(id);
        return Result.success(userWork);
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改用户工作经历", notes = "修改用户工作经历")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.DEFAULT_ROLE})
    public Result update(@RequestBody UserWorkUpdateRequest request) {
        LocalDate startDateTime = OtherUtils.transform(request.getStartDate());
        LocalDate endDateTime = OtherUtils.transform(request.getEndDate());

        UserWork userWork = userWorkService.getById(request.getId());
        userWork.setDescription(request.getDescription());
        userWork.setCertifier(request.getCertifier());
        userWork.setStartDate(startDateTime);
        userWork.setEndDate(endDateTime);
        userWork.setSideline(request.getSideline());
        return Result.success(userWorkService.updateById(userWork));
    }



}
